package com.springboot.cloud.demos.feign.events;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.jiguang.JpushUtil;
import com.springboot.cloud.demos.entity.enums.MessageType;
import com.springboot.cloud.demos.entity.form.MessageForm;
import com.springboot.cloud.demos.entity.form.UserQueryForm;
import com.springboot.cloud.demos.entity.po.*;
import com.springboot.cloud.demos.feign.config.BusConfig;
import com.springboot.cloud.demos.feign.service.MessageService;
import com.springboot.cloud.demos.feign.service.MomentService;
import com.springboot.cloud.demos.feign.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@Slf4j

public class MessageRabbitReceiver {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private MomentService momentService;
    @Autowired
    private JpushUtil jpushUtil;

    @RabbitListener(queues = BusConfig.QUEUE_NAME_FOLLOW)
    @RabbitHandler
    public void processFollow(String message) {
        log.info("Receiver follow: {}", message);
        //构建message
        Follow follow = JSONObject.parseObject(message, Follow.class);
        Result<User> result = userService.getById(follow.getUserId());
        Result<User> result2 = userService.getById(follow.getFollowUserId());
        if (result.isSuccess()) {
            User user = result.getData();
            User user2 = result2.getData();
            MessageForm message1 = new MessageForm();
            message1.setContent(user.getNickname() + "偷偷关注了你");
            message1.setFromUserId(follow.getUserId());
            message1.setToUserId(follow.getFollowUserId());
            message1.setType(MessageType.MESSAGE_TYPE_FOLLOW.getCode());
            message1.setValueId(follow.getUserId());
            String title = user.getNickname() + "偷偷关注了你";
            message1.setTitle(title);
            Result<Message> message2Re = messageService.save(message1);
            if (message2Re.isSuccess()) {
                Message message2 = message2Re.getData();
                jpushUtil.send(jpushUtil.buildMessagePayLoad(user2.getRegistrationId(), message2.getId(), title));
            }

        }
    }

    /**
     * 处理点赞消息
     */

    @RabbitListener(queues = BusConfig.QUEUE_NAME_SUPPORT)
    @RabbitHandler
    public void processSupport(String message) {
        log.info("Receiver support: {}", message);
        //构建message
        MomentSupport momentSupport = JSONObject.parseObject(message, MomentSupport.class);
        Result<User> result = userService.getById(momentSupport.getUserId());

        Result<Moment> result2 = momentService.get(momentSupport.getMomentId());

        if (result.isSuccess()) {
            User user = result.getData();
            Moment moment = result2.getData();
            Result<User> result3 = userService.getById(moment.getUserId());
            User user2 = result3.getData();
            MessageForm message1 = new MessageForm();
            message1.setContent(moment.getTitle());
            message1.setFromUserId(momentSupport.getUserId());
            message1.setToUserId(moment.getUserId());
            message1.setType(MessageType.MESSAGE_TYPE_SUPPORT.getCode());
            message1.setValueId(moment.getId());
            message1.setValueType(moment.getType());
            String title = user.getNickname() + "赞了你的动态\"" + moment.getTitle() + "\"";
            message1.setTitle(title);
            Result<Message> message2Re = messageService.save(message1);
            if (message2Re.isSuccess()) {
                Message message2 = message2Re.getData();
                jpushUtil.send(jpushUtil.buildMessagePayLoad(user2.getRegistrationId(), message2.getId(), title));
            }
        }
    }

    /**
     * 处理报名消息
     */

    @RabbitListener(queues = BusConfig.QUEUE_NAME_SIGNUP)
    @RabbitHandler
    public void processSignUp(String message) {
        log.info("Receiver support: {}", message);
        //构建message
        MomentSupport momentSupport = JSONObject.parseObject(message, MomentSupport.class);
        Result<User> result = userService.getById(momentSupport.getUserId());

        Result<Moment> result2 = momentService.get(momentSupport.getMomentId());

        if (result.isSuccess()) {
            User user = result.getData();
            Moment moment = result2.getData();
            Result<User> result3 = userService.getById(moment.getUserId());
            User user2 = result3.getData();
            MessageForm message1 = new MessageForm();
            message1.setContent(moment.getTitle());
            message1.setFromUserId(momentSupport.getUserId());
            message1.setToUserId(moment.getUserId());
            message1.setType(MessageType.MESSAGE_TYPE_SIGN_UP.getCode());
            message1.setValueId(moment.getId());
            message1.setValueType(moment.getType());
            String title = user.getNickname() + "报名了你的活动\"" + moment.getTitle() + "\"";
            message1.setTitle(title);
            Result<Message> message2Re = messageService.save(message1);
            if (message2Re.isSuccess()) {
                Message message2 = message2Re.getData();
                jpushUtil.send(jpushUtil.buildMessagePayLoad(user2.getRegistrationId(), message2.getId(), title));
            }
        }
    }

    /**
     * 处理评论消息
     */

    @RabbitListener(queues = BusConfig.QUEUE_NAME_COMMENT)
    @RabbitHandler
    public void processComment(String message) {
        log.info("Receiver comment: {}", message);
        //构建message
        MomentComment momentSupport = JSONObject.parseObject(message, MomentComment.class);
        Result<User> result = userService.getById(momentSupport.getUserId());

        Result<Moment> result2 = momentService.get(momentSupport.getMomentId());

        if (result.isSuccess()) {
            User user = result.getData();
            Moment moment = result2.getData();
            Result<User> result3 = userService.getById(moment.getUserId());
            User user2 = result3.getData();
            MessageForm message1 = new MessageForm();
            message1.setContent(moment.getTitle());
            message1.setFromUserId(momentSupport.getUserId());
            message1.setToUserId(moment.getUserId());
            message1.setType(MessageType.MESSAGE_TYPE_COMMENT.getCode());
            message1.setValueId(moment.getId());
            message1.setValueType(moment.getType());
            String title2 = "";
            if (moment.getTitle() != null) {
                if (moment.getTitle().length() > 10) {
                    title2 = moment.getTitle().substring(0, 10);
                } else {
                    title2 = moment.getTitle();
                }
            } else {
                title2 = "";
            }
            String title = user.getNickname() + "评论了你的动态\"" +title2 +"\":" + momentSupport.getContent();
            message1.setTitle(title);
            Result<Message> message2Re = messageService.save(message1);
            if (message2Re.isSuccess()) {
                Message message2 = message2Re.getData();
                jpushUtil.send(jpushUtil.buildMessagePayLoad(user2.getRegistrationId(), message2.getId(), title));
            }
        }
    }

    /**
     * 处理消息推送（发布消息，推送给关注者）
     */

    @RabbitListener(queues = BusConfig.QUEUE_NAME_PUSH)
    @RabbitHandler
    public void processPush(String message) {
        log.info("Receiver push: {}", message);
        //构建message
        Moment moment = JSONObject.parseObject(message, Moment.class);
        Result<User> result = userService.getById(moment.getUserId());

        if (result.isSuccess()) {
            User user = result.getData();
            UserQueryForm queryForm = new UserQueryForm();
            queryForm.setSize(100);
            queryForm.setCurrent(1);
            queryForm.setFollowUserId(user.getId());
            Result<Page> result1 = userService.getFollowMe(queryForm);
            log.info("用户{}的关注者信息: {}", user.getNickname(), result1.toString());
            if (result1.isSuccess()) {
                Page page = result1.getData();
                List<Map> list = page.getRecords();
                log.info("用户{}的关注者数量: {}", user.getNickname(), list.size());
                for (Map map : list) {
                    String regId = map.get("registrationId").toString();
                    String nickname = map.get("nickname").toString();
                    log.info("向{}{}推送消息",regId,nickname);
                    log.info("作者的RegistrationId：{}",user.getRegistrationId());
                    if(regId.equalsIgnoreCase(user.getRegistrationId())){return;}
                    jpushUtil.send(jpushUtil.buildMessagePayLoad(regId, moment.getId(),"你的好友"+user.getNickname()+"发布了一条动态："+moment.getTitle()));
                }

            } else {
                log.error("获取用户{}的关注者列表出错:{}", user.getNickname(), result1.getMesg());
            }

        }

    }

}
